package com.auto.autoapp.network

/**
 * 网络请求结果封装类
 * 用于统一处理网络请求的成功、失败和加载状态
 */
sealed class NetworkResult<out T> {
    /**
     * 成功状态
     * @param data 返回的数据
     */
    data class Success<out T>(val data: T) : NetworkResult<T>()
    
    /**
     * 错误状态
     * @param message 错误信息
     * @param code 错误码
     */
    data class Error(val message: String, val code: Int? = null) : NetworkResult<Nothing>()
    
    /**
     * 加载中状态
     */
    data object Loading : NetworkResult<Nothing>()
}

/**
 * 扩展函数：判断是否为成功状态
 */
fun <T> NetworkResult<T>.isSuccess(): Boolean = this is NetworkResult.Success

/**
 * 扩展函数：判断是否为错误状态
 */
fun <T> NetworkResult<T>.isError(): Boolean = this is NetworkResult.Error

/**
 * 扩展函数：判断是否为加载中状态
 */
fun <T> NetworkResult<T>.isLoading(): Boolean = this is NetworkResult.Loading

/**
 * 扩展函数：获取成功状态的数据，如果不是成功状态则返回 null
 */
fun <T> NetworkResult<T>.getDataOrNull(): T? = when (this) {
    is NetworkResult.Success -> data
    else -> null
}

/**
 * 扩展函数：执行成功回调
 */
inline fun <T> NetworkResult<T>.onSuccess(action: (T) -> Unit): NetworkResult<T> {
    if (this is NetworkResult.Success) {
        action(data)
    }
    return this
}

/**
 * 扩展函数：执行错误回调
 */
inline fun <T> NetworkResult<T>.onError(action: (String, Int?) -> Unit): NetworkResult<T> {
    if (this is NetworkResult.Error) {
        action(message, code)
    }
    return this
}

/**
 * 扩展函数：执行加载中回调
 */
inline fun <T> NetworkResult<T>.onLoading(action: () -> Unit): NetworkResult<T> {
    if (this is NetworkResult.Loading) {
        action()
    }
    return this
}


